﻿using System.IO;
using System.Linq;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using SMARTMobile.Common;
using SMARTMobile.Framework;
using SMARTMobile.Models;
using SMARTMobile.Utilities;
using SMARTMobile.ViewModels;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Media.Imaging;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;
using SmartMobile.Data;

namespace SMARTMobile.Views
{
    public partial class MainPage
    {
        private double _dragDistanceToOpen = 75.0;
        private double _dragDistanceToClose = 300.0;
        private double _dragDistanceNegative = -75.0;

        private bool _isSidebarVisible = false;
        private bool _isSidebarButtonClicked = false;
        SmartMobileDBContext _smartMobileContext;
        private FrameworkElement _feContainer;
        PhotoChooserTask selectphoto = null;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            _feContainer = this.Container as FrameworkElement;
            //SMARTMobile.Services.SMARTMobileServiceReference.ReloadDataSmartPhoneSoapClient servicesClient = new ReloadDataSmartPhoneSoapClient();
            //servicesClient.GetMenuCompleted += servicesClient_GetMenuCompleted;
            //servicesClient.GetMenuAsync();
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();

            this.MenuList = new List<MenuModel>();

            MenuModel list1 = new MenuModel();
            list1.Title = "Thiết đặt";
            this.MenuList.Add(list1);
            MenuModel list2 = new MenuModel();
            list2.Title = "Đồng bộ";
            this.MenuList.Add(list2);

            QuyTrinhPanel.Visibility = System.Windows.Visibility.Visible;
            KhachHangPanel.Visibility = System.Windows.Visibility.Collapsed;
            TacVuPanel.Visibility = System.Windows.Visibility.Collapsed;

            this.CreateConnection();
            this.Loaded += MainPage_Loaded;
        }

        public void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.DistributorWindow.WindowSize = new Size(Application.Current.RootVisual.RenderSize.Width, double.NaN);
        }

        protected override void OnPageLoaded(RoutedEventArgs e)
        {
            var viewModel = SMModelLocator.Instance.Main;
            if (viewModel == null)
                return;

            viewModel.MessageBoxRequest += this.MyView_MessageBoxRequest;
            viewModel.SidebarStateChanged += this.RaiseSidebarStateChanged;
        }

        protected override void OnPageUnloaded(RoutedEventArgs e)
        {
            var viewModel = SMModelLocator.Instance.Main;
            if (viewModel == null)
                return;

            viewModel.MessageBoxRequest -= this.MyView_MessageBoxRequest;
            viewModel.SidebarStateChanged -= this.RaiseSidebarStateChanged;
        }

        private void RaiseSidebarStateChanged(object obj)
        {
            if (obj != null && obj.ToString() == "Tap")
            {
                VisualStateManager.GoToState(this, "SidebarClosedState", true);
                this._isSidebarVisible = false;
                this._isSidebarButtonClicked = false;
                _isSettingsOpen = false;
            }

            if (this._isSidebarVisible)
            {
                // VisualStateManager.GoToState(this, "SidebarClosedState", true);
                this._isSidebarVisible = false;
                this._isSidebarButtonClicked = false;
                _isSettingsOpen = false;
            }
            else
            {
                VisualStateManager.GoToState(this, "SidebarOpenState", true);
                this._isSidebarButtonClicked = true;
                this._isSidebarVisible = true;
                _isSettingsOpen = true;
            }
        }

        void MyView_MessageBoxRequest(object sender, EventArgs e)
        {
            MessageBox.Show(sender.ToString());
        }

        public List<MenuModel> MenuList { get; private set; }

        private bool _isSettingsOpen = false;

        private void CloseSettings()
        {
            ////var trans = _feContainer.GetHorizontalOffset().Transform;
            ////trans.Animate(trans.X, 0, TranslateTransform.XProperty, 300, 0, new CubicEase
            ////{
            ////    EasingMode = EasingMode.EaseOut
            ////});

            _isSettingsOpen = false;
        }

        private void OpenSettings()
        {
            ////var trans = _feContainer.GetHorizontalOffset().Transform;
            ////trans.Animate(trans.X, 300, TranslateTransform.XProperty, 300, 0, new CubicEase
            ////{
            ////    EasingMode = EasingMode.EaseOut
            ////});

            _isSettingsOpen = true;
        }

        private void QuyTrinh_Click(object sender, RoutedEventArgs e)
        {
            //this._isSidebarButtonClicked = true;
            if (!_isSidebarVisible)
            {
                ////OpenSettings();
                QuyTrinhPanel.Visibility = System.Windows.Visibility.Visible;
                KhachHangPanel.Visibility = System.Windows.Visibility.Collapsed;
                TacVuPanel.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                if (QuyTrinhPanel.Visibility == System.Windows.Visibility.Visible)
                {
                    ////CloseSettings();
                }
                else
                {
                    QuyTrinhPanel.Visibility = System.Windows.Visibility.Visible;
                    KhachHangPanel.Visibility = System.Windows.Visibility.Collapsed;
                    TacVuPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        private void btnKhachHang_Click(object sender, RoutedEventArgs e)
        {
            //this._isSidebarButtonClicked = true;
            if (!this._isSidebarVisible)
            {
                ////OpenSettings();
                KhachHangPanel.Visibility = System.Windows.Visibility.Visible;
                QuyTrinhPanel.Visibility = System.Windows.Visibility.Collapsed;
                TacVuPanel.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                if (KhachHangPanel.Visibility == System.Windows.Visibility.Visible)
                {
                    ////CloseSettings();
                }
                else
                {
                    KhachHangPanel.Visibility = System.Windows.Visibility.Visible;
                    QuyTrinhPanel.Visibility = System.Windows.Visibility.Collapsed;
                    TacVuPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        private void btnTacVu_Click(object sender, RoutedEventArgs e)
        {
            //this._isSidebarButtonClicked = true;
            if (!_isSidebarVisible)
            {
                ////OpenSettings();
                TacVuPanel.Visibility = System.Windows.Visibility.Visible;
                KhachHangPanel.Visibility = System.Windows.Visibility.Collapsed;
                QuyTrinhPanel.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                if (TacVuPanel.Visibility == System.Windows.Visibility.Visible)
                {
                    ////CloseSettings();
                }
                else
                {
                    TacVuPanel.Visibility = System.Windows.Visibility.Visible;
                    KhachHangPanel.Visibility = System.Windows.Visibility.Collapsed;
                    QuyTrinhPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
            }

        }

        private void AvataImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.selectphoto = new PhotoChooserTask();
            this.selectphoto.Completed += selectphoto_Completed;
            this.selectphoto.Show();
        }

        private void selectphoto_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.ChosenPhoto);

                if (GlobalInformation.ArSaleSPType != null)
                {
                    string fileAvatarName = ImageUtilities.CreateImageName();
                    if (!string.IsNullOrEmpty(fileAvatarName))
                    {
                        ImageUtilities.SaveToJpeg(image, fileAvatarName);
                    }
                }

                this.AvataImage.Source = image;
            }
        }

        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Terminate();
        }

        private void DuLieu_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/NhapDuLieuPage.xaml", UriKind.Relative));
        }

        private void LayoutRoot_OnTap(object sender, GestureEventArgs e)
        {
            if (this._isSidebarButtonClicked && !this._isSidebarVisible)
            {
                VisualStateManager.GoToState(this, "SidebarClosedState", true);
                //this._isSidebarVisible = false;
                this._isSidebarButtonClicked = false;
                _isSettingsOpen = false;
            }

            this._isSidebarVisible = false;
        }

        private void CompanyText_Tap(object sender, GestureEventArgs e)
        {
            if (GlobalInformation.ArSaleSPType.Usertype == "SS")
            {
                List<Distributor> distributor = new List<Distributor>();
                distributor = _smartMobileContext.Distributor.ToList();

                if (distributor == null)
                {
                    MessageBox.Show("Không có dữ liệu công ty");
                }
                else
                {
                    this.DistributorListBox.ItemsSource = distributor;
                    this.DistributorWindow.IsOpen = true;
                }                
            }
        }

        private void DistributorListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //(this.DataContext as MainViewModel).CheckNewDevice();

            Distributor selectedDis = new Distributor();
            selectedDis = this.DistributorListBox.SelectedItem as Distributor;
            
            ARSALESPTYPE currentSale = this._smartMobileContext.ARSALESPTYPE.FirstOrDefault();

            if (GlobalInformation.ArSaleSPType == null)
            {
                GlobalInformation.ArSaleSPType = currentSale;
            }

            // Delete old data
            this._smartMobileContext.ARSALESPTYPE.DeleteOnSubmit(currentSale);
            this._smartMobileContext.SubmitChanges();

            ARSALESPTYPE saleSpType = null;

            if (selectedDis != null)
            {
                ARSALESPTYPE after = GlobalInformation.ArSaleSPType;
                saleSpType = new ARSALESPTYPE
                {
                    ID_PK = Guid.NewGuid(),
                    IMEIID = GlobalInformation.ArSaleSPType.IMEIID,
                    Webserver = GlobalInformation.ArSaleSPType.Webserver,
                    Phonenumber = GlobalInformation.ArSaleSPType.Phonenumber,
                    Usertype = GlobalInformation.ArSaleSPType.Usertype,
                    Username = GlobalInformation.ArSaleSPType.Username,
                    Usercode = GlobalInformation.ArSaleSPType.Usercode,
                    Sitename = selectedDis.SiteName,
                    Sitecode = selectedDis.SiteCode
                };

                this._smartMobileContext.ARSALESPTYPE.InsertOnSubmit(saleSpType);
                this._smartMobileContext.SubmitChanges();
            }

            GlobalInformation.ArSaleSPType = saleSpType;
            this.DistributorWindow.IsOpen = false;
        }

        private void CreateConnection()
        {
            this._smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            this._smartMobileContext.CreateIfNotExists();
            this._smartMobileContext.LogDebug = true;
        }

        private void GestureListener_OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange > 0 && !_isSettingsOpen)
            {
                double offset = _feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offset > _dragDistanceToOpen)
                {
                    string test = string.Empty;
                    this.OpenSettings();
                    VisualStateManager.GoToState(this, "SidebarOpenState", true);
                    this._isSidebarButtonClicked = true;
                    this._isSidebarVisible = true;

                }

                else
                {
                    string test = string.Empty;
                    //_feContainer.SetHorizontalOffset(offset);
                }

            }

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange < 0 && _isSettingsOpen)
            {
                double offsetContainer = _feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offsetContainer < _dragDistanceToClose)
                {
                    string test = string.Empty;
                    this.CloseSettings();
                    VisualStateManager.GoToState(this, "SidebarClosedState", true);
                    //this._isSidebarVisible = false;
                    this._isSidebarButtonClicked = false;
                    this._isSidebarVisible = false;
                }
                //
                else
                {
                    string test = string.Empty;
                    //_feContainer.SetHorizontalOffset(offsetContainer);
                }

            }
        }

        private void GestureListener_OnDragStarted(object sender, DragStartedGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && _isSettingsOpen)
            {
            }
        }

        private void GestureListener_OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange > 0 && !_isSettingsOpen)
            {
                if (e.HorizontalChange < _dragDistanceToOpen)
                {
                    string test = string.Empty;
                    this.ResetLayoutRoot();
                }
                //
                else
                {
                    string test = string.Empty;
                    this.OpenSettings();
                    VisualStateManager.GoToState(this, "SidebarOpenState", true);
                    this._isSidebarButtonClicked = true;
                    this._isSidebarVisible = true;
                }
                //
            }

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange < 0 && _isSettingsOpen)
            {
                if (e.HorizontalChange > _dragDistanceNegative)
                {
                    string test = string.Empty;
                    this.ResetLayoutRoot();
                }
                //
                else
                {
                    string test = string.Empty;
                    this.CloseSettings();
                    VisualStateManager.GoToState(this, "SidebarClosedState", true);
                    //this._isSidebarVisible = false;
                    this._isSidebarButtonClicked = false;
                    this._isSidebarVisible = false;
                }
                //
            }
        }

        private void ResetLayoutRoot()
        {
            if (!_isSettingsOpen)
                _feContainer.SetHorizontalOffset(0.0);
            else
                _feContainer.SetHorizontalOffset(200.0);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            while (this.NavigationService.BackStack.Any())
            {
                this.NavigationService.RemoveBackEntry();
            }
        }
        private void HoTroButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/HoTroPage.xaml", UriKind.Relative));
        }
    }
}